package serverhelper;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;

import api.controller.IAutoservice;
import api.messages.Messager;
import controllers.Autoservice;


public class ServerHelper {
	
	
	private ArrayList<String> temp=new ArrayList<String>();
	private static ServerHelper server_helper;
	private ArrayList<String> serverAnswer=new ArrayList<String>();
	private static final String ILLEG_ARG="Illegal Argument Exception";
	private static final String INVOC_EXC="Invocation Target Exception";
	private static final String NO_SUCH_METHOD= "No Such Method";
	private static final String SEC_EXC="Security Exception";
	private IAutoservice autoservice=new Autoservice();
	
	private ServerHelper(){
		
		
	}
	
	public static ServerHelper getInstance(){
		if(server_helper==null){
			server_helper=new ServerHelper();
		}
		return server_helper;
	}
	
	public ArrayList<String> getServerAnswer(ArrayList<String> helpMap){
		serverAnswer.clear();
		
		try {
			String methodName=helpMap.get(0);
			
			if(helpMap.get(1)==null){
				temp.clear();
			temp.addAll((ArrayList<String>) autoservice.getClass().getMethod(methodName, null).invoke(autoservice, null));
			}else{
				temp.clear();
			temp.addAll((ArrayList<String>) autoservice.getClass().getMethod(methodName, String.class).invoke(autoservice, helpMap.get(1)));
			}
			
			serverAnswer.addAll(temp);
			
			
		
		} catch (IllegalAccessException e) {
			writerException(Messager.EXCEPTION_SERVER_THREAD);			
		}catch(IllegalArgumentException	e){
			writerException(ILLEG_ARG);
		}catch(InvocationTargetException e){
			writerException(INVOC_EXC);
		}catch(NoSuchMethodException e){
			writerException(NO_SUCH_METHOD);
		}catch(SecurityException e){
			writerException(SEC_EXC);
		}
		
		return serverAnswer;
	}
	
	private void writerException(String message){
		serverAnswer.clear();
		serverAnswer.add(message);
	}
}
